import Vue from 'vue';

const DEFAULT_OPTIONS = {
  domain: {
    placeholder: '请输入域名',
    label: '域名',
    defaultValue: 'www.',
    validatorRules: [
      { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
    ]
  },
  ip: {
    placeholder: '请输入IP',
    label: '域名',
    validatorRules: [
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ]
  }
};
Vue.component('my-form', {
  render(h) {
    // <-- h must be in scope

    let formItems = this.options.map(item => {
      if (Array.isArray(item)) {
        let colSpan = parseInt(24 / item.length);
        return (
          <el-row gutter={20}>
            {item.map(arrItem => {
              return (
                <el-col span={colSpan}>
                  {this.constructFormItem(arrItem)}
                </el-col>
              );
            })}
          </el-row>
        );
      } else {
        return this.constructFormItem(item);
      }
    });
    return (
      <div>
        <el-form
          model={this.formModel}
          rules={this.rules}
          disabled={this.isReadOnly}
          ref="myForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          {formItems}
        </el-form>
        <el-row type="flex" class="row-bg" justify="end">
          {this.onCancel ? (
            <el-button onClick={this.onCancel}>{this.cancelText}</el-button>
          ) : (
            ''
          )}
          <el-button type="primary" onClick={this.onOkClick}>
            {this.okText}
          </el-button>
        </el-row>
      </div>
    );
  },
  data() {
    // 根据props：options 来构造data中的formModel和rules
    let options = this.options || [];
    let model = {};
    let rules = {};
    for (let item of options) {
      if (Array.isArray(item)) {
        for (let subitem of item) {
          this.constructModelAndRules(model, rules, subitem);
        }
      } else {
        this.constructModelAndRules(model, rules, item);
      }
    }

    return {
      formModel: model,
      rules: rules
    };
  },
  props: {
    options: {
      type: Array,
      required: true
    },
    onOk: {
      type: Function,
      required: true
    },
    isReadOnly: {
      type: Boolean,
      required: false,
      default: false
    },
    okText: {
      type: String,
      required: false,
      default: '确认'
    },
    cancelText: {
      type: String,
      required: false,
      default: '取消'
    },
    onCancel: {
      type: Function,
      required: false
    },
    formData: {
      type: Object,
      required: false
    }
  },
  methods: {
    // 传入的settings为props中options数组中的对象，基于该对象渲染一个输入组件
    constructFormItem(settings) {
      return (
        <el-form-item
          label={
            settings.label ||
            (DEFAULT_OPTIONS[settings.fieldType] || {}).label ||
            settings.keyName
          }
          prop={settings.keyName}
          required={settings.isRequired}
        >
          {settings.componentType == 'input' ? (
            <el-input
              v-model={this.formModel[settings.keyName]}
              placeholder={
                settings.placeholder ||
                (DEFAULT_OPTIONS[settings.fieldType] || {}).placeholder
              }
            />
          ) : (
            ''
          )}

          {settings.componentType == 'select' ? (
            <el-select v-model={this.formModel[settings.keyName]}>
              {(settings.options || []).map(option => (
                <el-option label={option.label} value={option.value} />
              ))}
            </el-select>
          ) : (
            ''
          )}
        </el-form-item>
      );
    },
    constructModelAndRules(model, rules, item) {
      if (this.formData) {
        let { keyName } = item;
        let keyNameArr = keyName.split('|');
        let tmp = JSON.parse(JSON.stringify(this.formData));
        for (let key of keyNameArr) {
          tmp = tmp[key];
        }
        model[item.keyName] = tmp || '';
      } else {
        model[item.keyName] =
          item.defaultValue ||
          (DEFAULT_OPTIONS[item.fieldType] || {}).defaultValue ||
          '';
      }

      rules[item.keyName] = (
        (DEFAULT_OPTIONS[item.fieldType] || {}).validatorRules || []
      ).concat(item.rules || []);
    },
    onOkClick() {
      let spreadedData = this.spreadModel();
      this.$refs['myForm'].validate(valid => {
        this.onOk(valid, spreadedData);
      });
    },

    /**
     * 将formModel中以|分隔的keyName展开，例如：
     * {
     *    a|b : '1'
     * }
     * ==>
     * {
     *    a:{
     *      b:'1'
     *    }
     * }
     *
     * */

    spreadModel() {
      let ret = {};
      for (let keyName in this.formModel) {
        let keyNameArr = keyName.split('|');
        if (keyNameArr.length > 1) {
          let firstKey = keyNameArr[0];
          ret[firstKey] = ret[firstKey] || {};
          let tmpModel = ret[firstKey];
          for (let i = 1, len = keyNameArr.length; i < len; i++) {
            let t_keyName = keyNameArr[i];
            if (i == len - 1) {
              tmpModel[t_keyName] = this.formModel[keyName];
            } else {
              if (tmpModel[t_keyName]) {
              } else {
                tmpModel[t_keyName] = {};
              }
              tmpModel = tmpModel[t_keyName];
            }
          }
        } else {
          ret[keyName] = this.formModel[keyName];
        }
      }

      return ret;
    }
  }
});
